package eu.codlab.twitteirb;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TweetsAdapter extends BaseAdapter{
	private TwittEirbActivity _parent;

	public TweetsAdapter(TwittEirbActivity parent){
		_parent = parent;
	}
	@Override
	public int getCount() {
		return TwittEirbService.getService().getTweets().size();
	}

	@Override
	public Object getItem(int arg0) {
		return TwittEirbService.getService().getTweets().get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(final int arg0, View arg1, ViewGroup parent) {
		//Log.d("refresh list","getVIew");
		View v = arg1;
		if (v == null) {

			LayoutInflater vi = (LayoutInflater)_parent.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.tweet_item, null);
		}

		v.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

			}

		});
		Tweet item = (Tweet)getItem(arg0);

		byte [] avatar = TwittEirbService.getService().getAvatar(item.getLogin());
		if(avatar != null){
			ImageView i = (ImageView)v.findViewById(R.tweet.avatar);
			Bitmap b = BitmapFactory.decodeByteArray(avatar, 0, avatar.length);
			if(b != null)
				i.setImageBitmap(b);
			else
				i.setVisibility(View.INVISIBLE);
		}

		TextView title = (TextView)v.findViewById(R.tweet.text);
		if(item.getText() != null && (item.getText().indexOf("@all") >=0 ||
				(TwittEirbService.getService().getLogin() != null &&
				TwittEirbService.getService().getLogin().length()>0 && 
				item.getText().indexOf("@"+TwittEirbService.getService().getLogin()) >=0)))
			v.setBackgroundColor(0xfff7f2b2);
		else
			v.setBackgroundColor(0xffffffff);
		title.setText(Html.fromHtml(""+item.getText()));
		title = (TextView)v.findViewById(R.tweet.date);
		title.setText(""+item.getDate());
		title = (TextView)v.findViewById(R.tweet.login);
		title.setText(""+item.getLogin());
		return v;
	}

}
